import React from 'react';
import { Table, Form, Input, Select, Button, Popconfirm, Switch } from 'antd';
import { connect } from 'dva';
import ModalC from 'components/Modal/equipment/equipment';
import ModalWebshell from 'components/Modal/webshell';
import ModalSynDev from 'components/Modal/equipment/syndevice';
import Authorized, { checkAuthority } from 'utils/Authorized';
import moment from 'moment';

const Item = Form.Item;
const Option = Select.Option;

@connect(state => ({
  equipment: state.equipment,
  global: state.global,
}))
class Pages extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      groupId: null,
      visible: false,
      drawerVisible: false,
      synDevVisble: false,
      formatData: null,
      selectedRowKeys: [],
      type: 'add',
      currentId: null,
      backupList: [],
      switchLoading: false,
      btnLoading: false,
    };
  }

  /**
   * 获取所有设备组列表
   */
  getAllEquipment = () => {
    this.props.dispatch({
      type: 'equipment/getAllList',
      payload: {},
      callback: data => {
        this.setState(
          {
            groupId: data.id,
          },
          () => this.getList()
        );
      },
    });
  };

  /**
   * 获取所有的备份服务器
   */
  getbackupList = (pageNum = 1, pageSize = 10) => {
    this.props.dispatch({
      type: 'backupService/getList',
      payload: {
        pageNum,
        pageSize,
      },
      callback: data => {
        this.setState({
          backupList: data,
        });
      },
    });
  };

  /**
   * 筛选
   */
  select = value => {
    this.setState(
      {
        groupId: value,
      },
      () => this.getList()
    );
  };

  //获取列表数据
  getList = () => {
    const { groupId } = this.state;
    this.props.dispatch({
      type: 'equipment/getList',
      payload: {
        groupId,
      },
    });
  };

  //提交数据
  submit = values => {
    const { type, currentId } = this.state;
    //debugger
    if (type === 'add') {
      this.props.dispatch({
        type: 'equipment/add',
        payload: {
          ...values,
        },
        callback: () => {
          this.setState(
            {
              groupId: values.groupId,
            },
            () => this.getList()
          );
          this.closeModal();
        },
      });
    } else {
      this.props.dispatch({
        type: 'equipment/edit',
        payload: {
          ...values,
          id: currentId,
        },
        callback: () => {
          this.getList();
          this.closeModal();
        },
      });
    }
  };

  /**
   * 删除
   */
  delete = ids => {
    this.props.dispatch({
      type: 'equipment/delete',
      payload: {
        ids,
      },
      callback: () => {
        this.setState({
          selectedRowKeys: [],
        });
        this.getList();
      },
    });
  };
  deleteAll = () => {
    const { selectedRowKeys } = this.state;
    this.delete(selectedRowKeys);
  };
  //批量删除
  onSelectChange = selectedRowKeys => {
    this.setState({ selectedRowKeys });
  };

  /**
   * modal
   */
  closeModal = () => {
    this.setState({
      visible: false,
      formatData: null,
    });
  };
  //新增编辑
  updateBtn = (type = 'add', record = null) => {
    if (type === 'add') {
      this.setState({
        type: 'add',
        visible: true,
      });
    } else {
      //debugger
      this.setState({
        type: 'edit',
        currentId: record.id,
        visible: true,
        formatData: record,
      });
    }
  };

  /**
   * webssh
   */
  connectWebssh = id => {
    this.setState({
      currentId: id,
    });
    this.props.dispatch({
      type: 'equipment/getToken',
      payload: {
        id,
      },
      callback: data => {
        this.setState(
          {
            token: data,
          },
          () => this.toggleDrawerVisible()
        );
      },
    });
  };

  /**
   *切换主设备
   */
  handleSwitch = id => {
    this.setState({
      switchLoading: true,
      currentId: id,
    });
    this.props.dispatch({
      type: 'equipment/toggleMainD',
      payload: {
        deviceId: id,
      },
      callback: () => {
        this.getList();
        this.setState({
          switchLoading: false,
          currentId: null,
        });
      },
    });
  };

  toggleDrawerVisible = () => {
    this.setState({
      drawerVisible: !this.state.drawerVisible,
    });
  };

  /**
   * 同步设备
   */
  synOpen = id => {
    this.setState({
      btnLoading: true,
      currentId: id,
    });
    this.props.dispatch({
      type: 'equipment/getAllDevices',
      callback: () => {
        this.setState(
          {
            btnLoading: false,
          },
          () => this.toggleSynModal()
        );
      },
    });
  };
  toggleSynModal = () => {
    this.setState({
      synDevVisble: !this.state.synDevVisble,
    });
  };
  //提交请求
  submitSyn = deviceIds => {
    debugger;
    const { currentId } = this.state;
    this.props.dispatch({
      type: 'equipment/synDevice',
      payload: {
        ...deviceIds,
        deviceId: currentId,
      },
      callback: () => this.toggleSynModal(),
    });
  };

  componentDidMount() {
    this.getAllEquipment();
    this.getbackupList();
  }

  render() {
    const {
      equipment: { list, loading, allList, btnLoading, allDevList },
    } = this.props;
    const {
      groupId,
      backupList,
      visible,
      formatData,
      selectedRowKeys,
      drawerVisible,
      token,
      currentId,
      switchLoading,
      synDevVisble,
    } = this.state;

    const colomns = [
      {
        title: '所属设备组',
        dataIndex: 'groupId',
        render: (text, record) => (
          <span>{allList.length > 0 && allList.filter(item => item.id === text)[0].groupName}</span>
        ),
      },
      {
        title: '设备名称',
        dataIndex: 'deviceName',
      },
      {
        title: '设备IP',
        dataIndex: 'deviceIp',
      },
      {
        title: '备份服务器',

        render: (text, record) => (
          <span>{record.hasOwnProperty('backupServerVO') && record.backupServerVO.serverIp}</span>
        ),
      },
      {
        title: '支持端口',
        dataIndex: 'serverPort',
      },
      {
        title: '用户名',
        dataIndex: 'userName',
      },
      {
        title: '设备位置',
        dataIndex: 'location',
      },
      {
        title: '白名单',
        dataIndex: 'whiteList',
      },
      {
        title: '备注',
        dataIndex: 'remark',
      },
      {
        title: '主设备',
        dataIndex: 'mainDevice',
        // width: 100,
        render: (text, record) => (
          <Switch
            loading={switchLoading && currentId === record.id}
            disabled={text === 1}
            onChange={() => this.handleSwitch(record.id)}
            checked={text === 1}
            checkedChildren="是"
            unCheckedChildren="否"
          />
        ),
      },

      {
        title: '创建时间',
        dataIndex: 'createDate',
        // width: 100,
        render: text => <span>{moment(text).format('YYYY年MM月DD日')}</span>,
      },
      {
        title: '更新时间',
        dataIndex: 'updateDate',
        // width: 100,
        render: text => <span>{moment(text).format('YYYY年MM月DD日')}</span>,
      },
      {
        title: '操作',
        width: '300px',
        render: (text, record) => (
          <>
            <Button onClick={() => this.updateBtn('edit', record)} type="ghost">
              编辑
            </Button>
            <Authorized authority={() => checkAuthority('webssh')} noMatch={<div />}>
              <Button
                loading={btnLoading && currentId === record.id}
                className="ml5"
                type="primary"
                onClick={() => this.connectWebssh(record.id)}
              >
                WEBSSH
              </Button>
            </Authorized>
            <Button
              loading={this.state.btnLoading && currentId === record.id}
              className="ml5"
              onClick={() => this.synOpen(record.id)}
              type="ghost"
            >
              {(!this.state.btnLoading || currentId !== record.id) && '同步设备'}
            </Button>
          </>
        ),
      },
    ];

    const rowSelection = {
      columnWidth: 10,
      onChange: this.onSelectChange,
    };

    return (
      <>
        <h3 className="head">设备管理</h3>
        <div style={{ padding: '10px 20px' }}>
          <div style={{ display: 'block', marginBottom: '20px' }}>
            <span>设备组:</span>
            <Select
              value={groupId}
              onChange={this.select}
              style={{ width: '150px', marginLeft: '10px' }}
            >
              {allList.map(item => (
                <Option value={item.id} key={item.id}>
                  {item.groupName}
                </Option>
              ))}
            </Select>
          </div>

          {selectedRowKeys.length > 0 && (
            <Popconfirm
              title="确定要删除吗？"
              okText="确定"
              cancelText="取消"
              onConfirm={() => this.deleteAll()}
            >
              <Button type="primary" icon="delete">
                批量删除
              </Button>
            </Popconfirm>
          )}

          <Table
            scroll={{ x: 1400 }}
            rowKey="id"
            style={{ marginBottom: '50px' }}
            loading={loading}
            columns={colomns}
            dataSource={list}
            rowSelection={rowSelection}
            pagination={false}
          />
          <Button type="primary" onClick={() => this.updateBtn()}>
            新增
          </Button>

          <ModalC
            list={allList}
            backupList={backupList}
            visible={visible}
            close={this.closeModal}
            formatData={formatData}
            submit={this.submit}
          />
          <ModalWebshell token={token} visible={drawerVisible} close={this.toggleDrawerVisible} />

          <ModalSynDev
            visible={synDevVisble}
            close={this.toggleSynModal}
            submit={this.submitSyn}
            list={allDevList}
          />
        </div>
      </>
    );
  }
}

export default Pages;
